package com.tlscpro.zwt.interceptor;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger=Logger.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession httpSession = request.getSession();
        String serverToken = (String) httpSession.getAttribute("token");
        String clientToken = request.getHeader("token");
        if (serverToken == null || clientToken == null){
            logger.warn("用户token令牌不存在");
            return false;
        }
        //判断token是否一致
        if (serverToken.equals(clientToken)){
            Date date = new Date();
            //判断token是否过期
            if (date.getTime() - httpSession.getLastAccessedTime() < httpSession.getMaxInactiveInterval()){
                httpSession.setMaxInactiveInterval(1000*60*30);
                System.out.println("token未过期");
                return true;
            }else
                return false;
        }else
            return false;
    }
}
